package me.hys.service.system.impl;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import me.hys.base.ApiResult;
import me.hys.cons.ApiStatus;
import me.hys.dao.system.IAccountMapper;
import me.hys.entity.system.AccountEntity;
import me.hys.entity.system.UserEntity;
import me.hys.kits.CollectionKit;
import me.hys.service.chat.IChatManager;
import me.hys.service.system.IAccountManager;
import me.hys.service.system.IUserManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;

/**
 * Author: @author HYS . <br>
 * Date: 2015-9-26 下午6:09:31 . <br>
 * Function: 第三方账户
 */
@Service
@Transactional
class AccountManagerImpl implements IAccountManager {
	@Autowired
	private IAccountMapper accountMapper;
	@Autowired
	private IUserManager userManager;
	@Autowired
	private IChatManager chatManager;

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.service.system.IAccountManager#findMobile(java.lang.String)
	 */
	@Override
	public ApiResult checkAccount(String uid) {
		ApiResult apiResult = new ApiResult();
		List<String> list = accountMapper.findUserByUid(uid);
		if (CollectionKit.isNull(list)) {
			apiResult.setResult(ApiStatus.SUCCESS);
			apiResult.setMsg("该账户未绑定手机号");
		} else {
			apiResult.setResult(Integer.parseInt(list.get(0)));
			apiResult.setMsg("账户已经绑定了手机号");
		}
		return apiResult;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * me.hys.service.system.IAccountManager#saveAccount(me.hys.entity.system
	 * .AccountEntity)
	 */
	@Override
	public ApiResult saveAccount(AccountEntity entity) {
		ApiResult apiResult = new ApiResult();
		Map<String, Object> cond = Maps.newHashMap();
		// 判断手机号是否绑定
		cond.put("mobile", entity.getMobile());
		if (null != userManager.findOneByCond(cond)) {
			apiResult.setResult(ApiStatus.FAILED);
			apiResult.setMsg("该手机号已经被使用过了");
			return apiResult;
		}
		// 保存到第三方账号表
		accountMapper.saveAccount(entity);
		// 在用户表中保存一份
		UserEntity user = new UserEntity();
		user.setNickname(entity.getNickname());
		user.setMobile(entity.getMobile());
		user.setType(entity.getType());
		user.setRegtime(new Timestamp(System.currentTimeMillis()));
		int userid = userManager.saveOrUpdate(user);

		// 注册环信
		UserEntity ue = userManager.findOneByCond(cond);
		ApiResult result = chatManager.register(ue.getId() + "",
				entity.getMobile(), entity.getNickname());
		if (result.getResult() == ApiStatus.FAILED) {
			return result;
		}
		apiResult.setResult(userid);
		apiResult.setMsg("手机号绑定成功");
		return apiResult;
	}
}
